import {
    getInfo,
    login as apiLogin,
    fetchDashboardData as apiFetchDashboardData,
    fetchRoles as apiFetchRoles,
    addRole as apiAddRole,
    updateRole as apiUpdateRole,
    deleteRole as apiDeleteRole,
    fetchDashboardStats as apiFetchDashboardStats,
} from '../services/api'; // 引入 API

const user = {
    state() {
        return {
            userName: '',
            userRole: '',
            isLoggedIn: !!localStorage.getItem('authToken'),
            userInfo: null,
            lockerData: [],
            deliveryData: [],
            roles: [],
        };
    },
    mutations: {
        setUserName(state, userName) {
            state.userName = userName;
        },
        setLoginStatus(state, status) {
            state.isLoggedIn = status;
        },
        setUserRole(state, role) {
            state.userRole = role;
        },
        setUserInfo(state, info) {
            state.userInfo = info;
        },
        updateUserInfo(state, info) {
            state.userInfo = { ...state.userInfo, ...info };
        },
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo;
        },
        SET_DASHBOARD_DATA(state, { lockerData, deliveryData }) {
            state.lockerData = lockerData;
            state.deliveryData = deliveryData;
        },
        SET_ROLES(state, roles) {
            state.roles = roles;
        },
    },
    actions: {
        async login({ commit }, credentials) {
            const response = await apiLogin(credentials);
            commit('SET_USER_INFO', response.data);
            // 存储 token 到 localStorage
            localStorage.setItem('authToken', response.data.token);
            return response;
        },
        logout({ commit }) {
            localStorage.removeItem('authToken');
            commit('setLoginStatus', false);
            commit('setUserInfo', null);
            commit('setUserRole', '');
        },
        fetchUserInfo({ commit }) {
            return getInfo()
                .then(userInfo => {
                    if (userInfo && userInfo.code === 1) {
                        commit('setUserInfo', userInfo.data);
                        return userInfo.data;
                    } else {
                        throw new Error('Failed to fetch user info');
                    }
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                    throw error;
                });
        },
        async fetchDashboardData({ commit }) {
            const response = await apiFetchDashboardData();
            commit('SET_DASHBOARD_DATA', response.data);
        },
        async fetchRoles({ commit }) {
            const response = await apiFetchRoles();
            commit('SET_ROLES', response.data);
        },
        async addRole({ dispatch }, roleData) {
            await apiAddRole(roleData);
            dispatch('fetchRoles');
        },
        async updateRole({ dispatch }, roleData) {
            await apiUpdateRole(roleData);
            dispatch('fetchRoles');
        },
        async deleteRole({ dispatch }, roleId) {
            await apiDeleteRole(roleId);
            dispatch('fetchRoles');
        },
        async fetchDashboardStats({ commit }) {
            try {
                const response = await apiFetchDashboardStats();
                commit('SET_DASHBOARD_DATA', response.data);
                return response; // 确保返回 Promise
            } catch (error) {
                console.error('获取仪表盘统计数据失败:', error);
                throw error;
            }
        },
    },
    getters: {
        userRole: (state) => state.userRole,
        userInfo: (state) => state.userInfo,
        isLoggedIn: (state) => state.isLoggedIn,
        lockerData: (state) => state.lockerData,
        deliveryData: (state) => state.deliveryData,
        roles: (state) => state.roles,
    },
};

// 将订单模块添加到根 store
export default {
    modules: {
        user,
    },
};



